import { reqPhoneCode, reqUserRegister, reqUserLogin, reqLoginInfo, reqLogout } from "@/api"

const actions = {
    async getPhoneCode(context, phone) {
        let result = await reqPhoneCode(phone)
        if (result.code === 200) {
            context.commit('GETPHONECODE', result.data)
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },
    async getUserRegister(context, myData) {
        let result = await reqUserRegister(myData)
        if (result.code === 200) {
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },
    async getUserLogin(context, myData) {
        let result = await reqUserLogin(myData)
        if (result.code === 200) {
            console.log(result);
            localStorage.setItem('token', result.data.token)
            context.commit('REQUSERLOGIN', result.data.token)
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },
    async getLoginInfo(context) {
        let result = await reqLoginInfo()
        if (result.code === 200) {
            context.commit('GETLOGININFO', result.data)
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },
    async getUserLogout(context) {
        let result = await reqLogout()
        if (result.code === 200) {
            context.commit('GETUSERLOGOUT')
            return 'ok'
        }
        else {
            return Promise.reject(new Error('fail'))
        }
    },

}

const mutations = {
    GETPHONECODE(state, code) {
        state.code = code
    },
    REQUSERLOGIN(state, token) {
        state.token = token
    },
    GETLOGININFO(state, userInfo) {
        state.userInfo = userInfo
    },
    GETUSERLOGOUT(state) {
        state.token = '',
            state.userInfo = {},
            localStorage.removeItem('token')
    }

}

const state = {
    code: '',
    token: localStorage.getItem('token'),
    userInfo: {

    }
}

const getters = {

}

export default {
    actions,
    mutations,
    state,
    getters
}